<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>b 播放页面</title>
</head>

<body>
    <h4 id="nameID"></h4>
    <audio id="audioID" controls autoplay></audio>

    <script>
        let audioID = document.getElementById('audioID')
        let nameID = document.getElementById('nameID')
        let channel = new BroadcastChannel('music');

        function setName(name) {
            nameID.innerText = name;
        }

        function play(name) {
            audioID.src = './musics/' + name;
            audioID.play();
        }

        channel.addEventListener('message', (e) => {
            let name = e.data;
            if (name) {
                setName(name);
                play(name);
            }
        })

        window.addEventListener('load', () => {
            // 用此方式获取链接上的参数
            const params = new URLSearchParams(location.search);
            let name = params.get('name');
            if (name) {
                setName(name);
                play(name);

                let n = +localStorage.getItem('music');
                if (!isNaN(n)) {
                    n++;
                } else {
                    n = 1;
                }
                localStorage.setItem('music', n);
            }
        })

        window.addEventListener('unload', () => {
            let n = +localStorage.getItem('music');
            if (isNaN(n)) {
                n = 1;
            }
            n--;
            if (n <= 0) {
                n = 0;
            }
            localStorage.setItem('music', n);
        })

    </script>
</body>

</html>